from pathlib import Path

from .random_excel import *

from PySide6.QtCore import QThread, Signal
from office import excel
from tools import union_excel
from traceback import format_exc
from ...base import ThreadBase


class ExcelToPdfThread(ThreadBase):
    """Excel转pdf"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.excel_list = []
        self.save_path = None

    def run(self):
        try:
            for path in self.excel_list:
                excel.excel2pdf(path, self.save_path)
        except Exception as e:
            self.error.emit(e)

    def set_value(self, excel_list, save_path):
        self.excel_list = excel_list
        self.save_path = save_path


class MergeToExcelThread(ThreadBase):
    """Excel合并"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.dir_path, self.output_file = [], 'merge2excel.xlsx'

    def run(self):
        try:
            excel.merge2excel(self.dir_path, self.output_file)
        except Exception as e:
            self.error.emit(e)

    def set_value(self, dir_path: str, output_file: str):
        self.dir_path, self.output_file = dir_path, output_file


class SheepToExcelThread(ThreadBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.file_path, self.output_path = None, None

    def run(self):
        try:
            for file in self.file_path:
                fp = Path(self.output_path) / Path(file).stem
                fp.mkdir()
                excel.sheet2excel(file, fp)
        except Exception as e:
            self.error.emit(e)

    def set_value(self, file_path: str, output_path: str):
        self.file_path, self.output_path = file_path, output_path


class UnionQueryThread(ThreadBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.data = None
        self.save_path = None

    def run(self):
        try:
            union_excel(self.data, self.save_path)
        except Exception as e:
            self.error.emit(format_exc())

    def set_value(self, data, save_path):
        self.data = data
        self.save_path = save_path
